package org.smart4j.plugin.druid;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.ds.impl.AbstractDataSourceFactory;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 基于 Durid 的数据源工厂
 *
 * @author huangyong
 * @since 2.3
 */
public class DruidDataSourceFactory extends AbstractDataSourceFactory<DruidDataSource> {

    private static final Logger logger = LoggerFactory.getLogger(DruidDataSourceFactory.class);
    private static Object lockobject =new Object();
    private static DruidDataSource dds=null;
    @Override
    public DruidDataSource createDataSource() {
        try {
        	if (dds == null) {  
        		synchronized (lockobject) {
            		dds = (DruidDataSource)com.alibaba.druid.pool.DruidDataSourceFactory.createDataSource(readProperties("/druid.properties"));  
				}
            }  
			return dds;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }

    @Override
    public void setDriver(DruidDataSource ds, String driver) {
        ds.setDriverClassName(driver);
    }

    @Override
    public void setUrl(DruidDataSource ds, String url) {
        ds.setUrl(url);
    }

    @Override
    public void setUsername(DruidDataSource ds, String username) {
        ds.setUsername(username);
    }

    @Override
    public void setPassword(DruidDataSource ds, String password) {
        ds.setPassword(password);
    }

    @Override
    public void setAdvancedConfig(DruidDataSource ds) {
        try {
            ds.setFilters("stat");
        } catch (SQLException e) {
            logger.error("错误：设置 Stat Filter 失败！", e);
        }
    }

	private static Properties readProperties(String filePath) throws IOException {
		Properties props = new Properties();
		System.out.println(DruidDataSourceFactory.class.getResource(filePath));
		InputStream in = new BufferedInputStream(DruidDataSourceFactory.class.getResourceAsStream(filePath));
		props.load(in);
		return props;
	}
}
